﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using ClientTools.Library.Manager;
using umbraco;
using umbraco.uicontrols;

namespace ClientTools.Section.LogViewer
{
    public partial class LogViewer : Page
    {
        //private LogManager logManager;
        public TabPage FirstTab;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;

            FillHeaders();
            GetLogs();
        }

        protected override void OnInit(EventArgs e)
        {
            // Tab setup
            FirstTab = MainTab.NewTabPage("Client Tools for Umbraco: Log Viewer");
            FirstTab.Controls.Add(MainPane);

            txtComment.TextChanged += ReloadItems;
            cboLogHeader.SelectedIndexChanged += ReloadItems;

            ImageButton search = new MenuImageButton();
            search.Click += SearchClick;
            search.AlternateText = "Search";
            search.ImageUrl = GlobalSettings.Path + "/images/find.small.png";
            FirstTab.Menu.Controls.Add(search);

            ImageButton reset = new MenuImageButton();
            reset.Click += ResetClick;
            reset.AlternateText = "Reset Filter";
            reset.ImageUrl = GlobalSettings.Path + "/images/undo.small.png";
            FirstTab.Menu.Controls.Add(reset);

            ImageButton delete = new MenuImageButton();
            delete.Click += DeleteClick;
            delete.AlternateText = "Delete Entries";
            delete.ImageUrl = GlobalSettings.Path + "/images/delete_button.png";
            //delete.ImageUrl = GlobalSettings.Path + "/plugins/ClientTools/delete.gif";
            FirstTab.Menu.Controls.Add(delete);

        }

        private void DeleteClick(object sender, ImageClickEventArgs e)
        {
            DeleteLogs();
            GetLogs();
        }

        private void DeleteLogs()
        {
            var ids = new List<int>();
            foreach (GridViewRow row in GridView1.Rows)
                if (((CheckBox)row.FindControl("chkRows")).Checked)
                    ids.Add(int.Parse(row.Cells[1].Text));
            LogManager.DeleteLogsByIDs(ids.ToArray());
        }


        private void SearchClick(object sender, ImageClickEventArgs e)
        {
            GetLogs();
        }

        private void ResetClick(object sender, ImageClickEventArgs e)
        {
            txtUserId.Text = "";
            txtNodeId.Text = "";
            txtMaxItems.Text = "50";
            txtComment.Text = "";
            cboLogHeader.SelectedIndex = 0;
            txtStartDate.Text = "";
            txtEndDate.Text = "";
        }


        private void GetLogs()
        {
            int? maxrow = 20;
            DateTime? startdate = null;
            DateTime? enddate = null;
            string header = null;
            int? userid = null;
            int? nodeid = null;
            string comment = null;

            int tempInt;

            if (!string.IsNullOrEmpty(txtMaxItems.Text.Trim()))
                if (int.TryParse(txtMaxItems.Text.Trim(), out tempInt))
                    maxrow = tempInt;
                else
                {
                    ShowMessage("Max Rows is not a number!");
                    return;
                }

            if (!string.IsNullOrEmpty(txtNodeId.Text.Trim()))
                if (int.TryParse(txtNodeId.Text.Trim(), out tempInt))
                    nodeid = tempInt;
                else
                {
                    ShowMessage("Node ID is not a number!");
                    return;
                }

            if (!string.IsNullOrEmpty(txtUserId.Text.Trim()))
                if (int.TryParse(txtUserId.Text.Trim(), out tempInt))
                    userid = int.Parse(txtUserId.Text.Trim());
                else
                {
                    ShowMessage("User ID is not a number!");
                    return;
                }

            if (cboLogHeader.SelectedIndex > 0)
                header = cboLogHeader.SelectedItem.Text;

            DateTime tempDate;
            if (!string.IsNullOrEmpty(txtStartDate.Text.Trim()))
                if (DateTime.TryParse(txtStartDate.Text.Trim(), out tempDate))
                    startdate = tempDate;
                else
                {
                    ShowMessage("Startdate is not a date!");
                    return;
                }

            if (!string.IsNullOrEmpty(txtEndDate.Text.Trim()))
                if (DateTime.TryParse(txtEndDate.Text.Trim(), out tempDate))
                    enddate = tempDate;
                else
                {
                    ShowMessage("Enddate is not a date!");
                    return;
                }

            if (!string.IsNullOrEmpty(txtComment.Text.Trim()))
                comment = txtComment.Text.Trim();

            var logs = LogManager.GetLogs(startdate, enddate, header, userid, nodeid, maxrow, comment);

            ResultPanel.Width = Unit.Percentage(100);
            GridView1.DataSource = logs;
            GridView1.DataBind();
            GridView1.Width = Unit.Percentage(100);
            GridView1.Columns[4].ItemStyle.Width = Unit.Pixel(200);

            MessagePane.Visible = false;

            lblReturnedItems.Text = logs.Count.ToString();
        }

        private void ShowMessage(string s)
        {
            lblMessage.Text = s;
            MessagePane.Visible = true;
        }

        private void FillHeaders()
        {
            cboLogHeader.Items.Clear();
            var li = new ListItem(">> Select a header <<") {Value = "0"};
            cboLogHeader.Items.Add(li);

            foreach (var loginfo in LogManager.GetLogInfos())
                cboLogHeader.Items.Add(new ListItem {Text = loginfo.LogHeader, Value = loginfo.LogHeader});
        }

        protected void ReloadItems(object sender, EventArgs e)
        {
            GetLogs();
        }

    }
}
